import { Component, OnInit, ViewChild } from '@angular/core';
import { DValidateRules, TableWidthConfig, FormLayout, DataTableComponent, DrawerService, IDrawerOpenResult, DialogService } from '@devui';
import { ReviewDocComponent } from '../../basic-data/user-center/review-doc/review-doc.component';
import { SaleDeliver } from 'src/app/@core/data/sale';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import mockData from 'src/app/@core/data/mock-after-sales-deliveries.json';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

interface AfterSalesRecord {
  id: number;
  customerName: string;
  quantity: number;
  address: string;
  shipDate: Date | string;
  durationMonths: number;
  // 计算字段
  expireDate?: Date | string;
  daysLeft?: number;
  status?: '在保' | '过保';
}

@Component({
  selector: 'app-after-sales-center-component',
  templateUrl: './after-sales-center-component.component.html',
  styleUrls: ['./after-sales-center-component.component.scss']
})
export class AfterSalesCenterComponentComponent implements OnInit {
  pager = {
      total: 20,
      pageIndex: 1,
      pageSize: 20,
    };
    pageSizeOptions = [10, 20, 30, 50, 100];
    SaleDeliver: SaleDeliver = {
      saleDeliverId: 0, // 销售发货单ID
      orderDate: null, // 订单日期
      saleDeliverNum: '', // 销售发货单号
      saleDeliverCustomerId: 0, // 客户ID
      chineseName: '', // 客户中文名
      customerAbbreviation: '', // 客户简称
      company: '', // 公司名
      customerContactName: '', // 客户联系人姓名
      customerContactPhone: '', // 客户联系电话
      salesmanName: '', // 销售员姓名
      departmentName: '', // 部门名称
      scheduledDeliverTime: null, // 预定发货时间
      deliverType: '', // 发货类型
      deliveryAddress: '', // 发货地址
      settlementMethodName: '', // 结算方式名称
      currencyName: '', // 货币名称
      collectionPeriodName: '', // 收款期限名称
      isInvoice: false, // 是否开发票
      note: '', // 备注
      isPush: false, // 是否推送
      isDeliver: false, // 是否发货
      isReceive: false, // 是否收货
      isCancellation: false, // 是否取消
      isPrint: false, // 是否打印
      createTime: null, // 创建时间
      createUser: '', // 创建用户
      amount: 0, // 金额
      taxAmount: 0, // 税额
      tax: 0, // 税率
      unTaxAmount: 0, // 不含税金额
      taxDiscountAmount: 0, // 税后折扣金额
      taxDiscount: 0, // 税后折扣
      discountAmount: 0, // 折扣金额
      files: [], // 文件列表
      fileRemarks: [], // 文件备注
      saleDeliverParts: [], // 销售发货单零件列表
    };
    tableData = [];
    dataTableOptions = {
      columns: [
        {
          field: 'code',
          header: '操作',
          fieldType: 'text',
          fixedLeft: '80px',
        },
        {
          field: 'saleOrderNum',
          header: '销售订单号',
          fieldType: 'text',
        },
        {
          field: 'name',
          header: '销售发货单单号',
          fieldType: 'text',
          fixedLeft: '310px',
        },
  
        {
          field: '单据日期',
          header: '单据日期',
          fieldType: 'text',
        },
        {
          field: '客户简称',
          header: '客户简称',
          fieldType: 'text',
        },
        {
          field: '客户全称',
          header: '客户全称',
          fieldType: 'text',
        },
        {
          field: '业务员',
          header: '业务员',
          fieldType: 'text',
        },
        {
          field: '部门',
          header: '部门',
          fieldType: 'text',
        },
  
        {
          field: '客户联系人',
          header: '客户联系人',
          fieldType: 'text',
        },
        {
          field: '发货时间',
          header: '发货时间',
          fieldType: 'text',
        },
  
        {
          field: '结算方式',
          header: '结算方式',
          fieldType: 'text',
        },
        {
          field: '交货地址',
          header: '交货地址',
          fieldType: 'text',
        },
        {
          field: '客户是否到货',
          header: '客户是否到货',
          fieldType: 'text',
        },
        {
          field: '到货时间',
          header: '到货时间',
          fieldType: 'text',
        },
        {
          field: '发货时长(天)',
          header: '发货时长(天)',
          fieldType: 'text',
        },
        {
          field: '数量',
          header: '数量',
          fieldType: 'text',
        },
        {
          field: '金额合计',
          header: '金额合计',
          fieldType: 'text',
        },
        {
          field: '税额合计',
          header: '税额合计',
          fieldType: 'text',
        },
        {
          field: '不含税金额合计',
          header: '不含税金额合计',
          fieldType: 'text',
        },
        {
          field: '折扣含税金额合计',
          header: '折扣含税金额合计',
          fieldType: 'text',
        },
        {
          field: '折扣税额合计',
          header: '折扣税额合计',
          fieldType: 'text',
        },
        {
          field: '折扣不含税金额合计',
          header: '折扣不含税金额合计',
          fieldType: 'text',
        },
        {
          field: '二维码',
          header: '二维码',
          fieldType: 'text',
        },
        {
          field: '制单人',
          header: '制单人',
          fieldType: 'text',
        },
        {
          field: '制单日期',
          header: '制单日期',
          fieldType: 'text',
        },
        {
          field: '备注',
          header: '备注',
          fieldType: 'text',
        },
        {
          field: '日志',
          header: '日志',
          fieldType: 'text',
        },
        {
          field: '状态',
          header: '状态',
          fieldType: 'text',
          fixedRight: '0px',
        },
      ],
    }; //表格数据
    tableWidthConfig: TableWidthConfig[] = [
      {
        field: 'checkbox',
        width: '80px',
      },
      {
        field: '操作',
        width: '230px',
      },
      {
        field: '销售订单号',
        width: '160px',
      },
      {
        field: '销售发货单单号',
        width: '150px',
      },
      {
        field: '单据日期',
        width: '150px',
      },
      {
        field: '客户简称',
        width: '150px',
      },
      {
        field: '业务员',
        width: '150px',
      },
      {
        field: '部门',
        width: '150px',
      },
  
      {
        field: '预计发货时间',
        width: '200px',
      },
      {
        field: '收货人',
        width: '150px',
      },
      {
        field: '付款方式',
        width: '150px',
      },
      {
        field: '交货地址',
        width: '200px',
      },
      {
        field: '客户是否到货',
        width: '150px',
      },
      {
        field: '到货时间',
        width: '170px',
      },
      {
        field: '发货时长(天/半天)',
        width: '150px',
      },
      {
        field: '数量',
        width: '150px',
      },
  
      {
        field: '金额合计',
        width: '150px',
      },
      {
        field: '税额合计',
        width: '150px',
      },
      {
        field: '不含税金额合计',
        width: '150px',
      },
      {
        field: '折扣含税金额合计',
        width: '150px',
      },
      {
        field: '折扣税额合计',
        width: '150px',
      },
      {
        field: '折扣不含税金额合计',
        width: '150px',
      },
      {
        field: '二维码',
        width: '150px',
      },
      {
        field: '制单人',
        width: '150px',
      },
      {
        field: '制单日期',
        width: '150px',
      },
      {
        field: '日志',
        width: '200px',
      },
      {
        field: '审批',
        width: '100px',
      },
      {
        field: '审批',
        width: '100px',
      },
      {
        field: '状态',
        width: '150px',
      },
    ]; //表格宽度配置
    msgs: { severity: any; summary: any; content: any }[];
    @ViewChild(DataTableComponent, { static: true })
    datatable: DataTableComponent;
    checkedIds: any = [];
    fifter = {
      SearchTermPart: '',
      SearchTermCustomer: '',
      SearchStatus: '',
      SaleOrderNum: '',
      SaleDeliverNum: '',
      OrderDateStartTime: '',
      OrderDateEndTime: '',
      CreateTimeStartTime: '',
      CreateTimeEndTime: '',
      PageNumber: 1,
      PageSize: 20,
    };
    date = [];
    splitBarSize = '0px';
    partDetailHeight = '100%';
    showDetailId: any;
    selectedRowIndex: any;
    partDetail: any = [];
    tableWidthConfig2: TableWidthConfig[] = [
      {
        field: '物料编码',
        width: '200px',
      },
      {
        field: '图片',
        width: '150px',
      },
      {
        field: '物料名称',
        width: '150px',
      },
      {
        field: '规格型号',
        width: '150px',
      },
      {
        field: '物料描述',
        width: '150px',
      },
      {
        field: '计划发货日期',
        width: '200px',
      },
      {
        field: '实时库存',
        width: '150px',
      },
      {
        field: '数量',
        width: '170px',
      },
      {
        field: '单位',
        width: '150px',
      },
      {
        field: '单价(含税)',
        width: '170px',
      },
      {
        field: '单价（不含税）',
        width: '150px',
      },
      {
        field: '税率（%）',
        width: '170px',
      },
      {
        field: '折扣单价（含税）',
        width: '150px',
      },
      {
        field: '含税金额',
        width: '150px',
      },
      {
        field: '不含税金额',
        width: '150px',
      },
      {
        field: '税额',
        width: '150px',
      },
      {
        field: '折扣不含税金额',
        width: '150px',
      },
      {
        field: '折扣含税金额',
        width: '150px',
      },
      {
        field: '折扣税额',
        width: '150px',
      },
      {
        field: '备注',
        width: '150px',
      },
      {
        field: '来源报价单号',
        width: '150px',
      },
    ];
    checkedCodes: any = [];
    constructor(
      private SharedMethodService: SharedMethodService,
      private Router: Router,
      private SalesService: SalesService,
      private DialogService: DialogService,
      private drawerService: DrawerService,
      private ReviewRolesService: ReviewRolesService
    ) {}
    ngOnInit(): void {
      // 默认使用本地 mock 数据；若需对接 API，保留 filter()
      this.loadMock();
    }
    filter() {
      this.SalesService.GetPagedSaleDeliver(this.fifter).subscribe(
        (data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
        }
      );
    }
    private loadMock() {
      const items = (mockData as any).items || [];
      this.tableData = items.map((x: any) => ({
        ...x,
        // 运行时字段
        $checked: false,
        $halfChecked: false,
        // 计算发货时长（从 deliverTime 到 arrivalTime），单位天，向上取整
        deliverDurationDays: this.calcDurationDays(x.deliverTime, x.arrivalTime),
      }));
      this.pager.total = this.tableData.length;
    }

    private calcDurationDays(start?: string, end?: string): number | null {
      if (!start || !end) return null;
      const s = new Date(start).getTime();
      const e = new Date(end).getTime();
      if (isNaN(s) || isNaN(e)) return null;
      const hours = (e - s) / (1000 * 60 * 60);
      if (hours <= 0) return 0;
      // 半天为基本单位（12小时），向上取整到最近的半天
      // 例：1小时 -> 0.5天；12小时 -> 0.5天；13小时 -> 1天；25小时 -> 1.5天
      return Math.ceil(hours / 12) / 2;
    }
    filter2() {
      this.fifter.PageNumber = 1;
      this.SalesService.GetPagedSaleDeliver(this.fifter).subscribe(
        (data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
        }
      );
    }
    reset() {
      this.fifter = {
        SearchTermPart: '',
        SearchTermCustomer: '',
        SearchStatus: '',
        SaleOrderNum: '',
        SaleDeliverNum: '',
        OrderDateStartTime: '',
        OrderDateEndTime: '',
        CreateTimeStartTime: '',
        CreateTimeEndTime: '',
        PageNumber: 1,
        PageSize: 20,
      };
      this.date = [];
  // 若使用 mock，则刷新 mock；否则调 API
  this.loadMock();
    }
    creat() {
  // 演示环境：不跳转，保留原逻辑如需启用可还原
  // this.Router.navigate(['/pages/sales-master/sales-Invoice/add']);
    }
    edit(id: any) {
  // this.Router.navigate(['/pages/sales-master/sales-Invoice/edit', id]);
    }
    delete(id?: any, dialogtype?: string) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '400px',
        backdropCloseable: true,
        data: '',
        title: '删除',
        content: '删除后将无法恢复该数据！',
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (id) {
                this.SalesService.DeleteSaleDeliver([id]).subscribe(
                  (data: any) => {
                    this.filter();
                    this.showToast('success', '成功', '删除成功');
                  },
                  (error) => {
                    if (error.status == 404) {
                      this.showToast('error', '失败', '服务器连接失败');
                    } else {
                      this.showToast('error', '失败', error.error);
                    }
                  }
                );
              } else {
                this.SalesService.DeleteSaleOrders(this.checkedIds).subscribe(
                  (data: any) => {
                    this.filter();
                    this.showToast('success', '成功', '删除成功');
                  },
                  (error) => {
                    if (error.status == 404) {
                      this.showToast('error', '失败', '服务器连接失败');
                    } else {
                      this.showToast('error', '失败', error.error);
                    }
                  }
                );
              }
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    onRowCheckChange(
      checked: any,
      rowIndex: any,
      nestedIndex: any,
      rowItem: { $checked: any; $halfChecked: boolean }
    ) {
      this.SharedMethodService.onRowCheckChange(
        checked,
        rowIndex,
        nestedIndex,
        rowItem,
        this.datatable
      );
    }
    getCheckedRows() {
      this.SharedMethodService.getCheckedRows(
        this.datatable,
        'saleDeliverId'
      ).subscribe((data: any) => {
        this.checkedIds = data;
      });
      this.SharedMethodService.getCheckedRows(
        this.datatable,
        'saleDeliverNum'
      ).subscribe((data: any) => {
        this.checkedCodes = data;
      });
    } //获取选中行
    CheckedRows=[]
    getCheckedRowsData() {
      this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
        (data: any) => {
          this.CheckedRows = data;
        }
      );
    } //获取选中行
    cleared() {
      this.SharedMethodService.cleared(
        this.checkedIds,
        this.tableData,
        this.datatable
      ).subscribe((data: any) => {
        this.checkedIds = data;
      });
    } //清空选中行
    pageIndexChange($event: any) {
      this.filter();
    } //切换页码
    pageSizeChange($event: any) {
      this.filter();
    } //改变每页显示数量
    showToast(type: any, summary: any, content: any) {
      switch (type) {
        default:
          this.msgs = [{ severity: type, summary: summary, content: content }];
      }
    } //提示框
    FinishSaleDeliver(id: any, dialogtype?: string) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '400px',
        backdropCloseable: true,
        data: '',
        title: '发货',
        content: '确定要发货吗？',
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.SalesService.FinishSaleDeliver(id).subscribe(
                (data: any) => {
                  this.showToast('success', '成功', '发货成功');
                  this.filter();
                },
                (error) => {
                  if (error.status == 404) {
                    this.showToast('error', '失败', '服务器连接失败');
                  } else {
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    checkCustomerIDs(customerRows: any) {
      // 如果数组长度为1或为空，直接返回true
      if (customerRows.length <= 1) {
        return true;
      }
      // 获取第一个元素的customerID
      const firstCustomerID = customerRows[0].saleDeliverCustomerId;
      // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
      return customerRows.every((row: any) => row.customerID === firstCustomerID);
    }
    AuditSaleDeliver(id: any) {
      this.SalesService.AuditSaleDeliver(id).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '审核成功');
          this.filter();
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error.error.message);
          }
        }
      );
    }
    UnAuditSaleDeliver(id: any) {
      this.SalesService.UnAuditSaleDeliver(id).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '反审核成功');
          this.filter();
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error.error.message);
          }
        }
      );
    }
    results: IDrawerOpenResult;
    allLog() {
      this.SalesService.GetAllSaleDeliverLogs({
        PageNumber: 1,
        PageSize: 999,
      }).subscribe((data: any) => {
        const logData = data.items;
        const columns = [
          {
            field: '销售发货单',
            header: '销售发货单',
            fieldType: 'text',
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text',
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text',
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text',
          },
        ];
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: { data: logData, columns: columns },
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {},
        });
      });
    }
    GetLogsById(id: any) {
      this.SalesService.GetLogsBySaleDeliverId({
        Id: id,
        PageNumber: 1,
        PageSize: 9999,
      }).subscribe((data: any) => {
        const logData = data.items;
        const columns = [
          {
            field: '销售顶单',
            header: '销售顶单',
            fieldType: 'text',
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text',
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text',
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text',
          },
        ];
  
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: { data: logData, columns: columns },
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {},
        });
      });
    }
    dateChange() {
      this.fifter.CreateTimeStartTime = this.date[0]
        .toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
        })
        .replace(/\//g, '/');
      this.fifter.CreateTimeEndTime = this.date[1]
        .toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
        })
        .replace(/\//g, '/');
    }
    showDetail(data: any, rowIndex: any) {
      this.showDetailId = data.saleDeliverId;
      (this.partDetail = data.saleDeliverParts), (this.partDetailHeight = '75%');
      this.splitBarSize = '10px';
      this.selectedRowIndex = rowIndex;
    }
    // 到货操作：置 isReceive=true，记录 arrivalTime=当前，计算发货时长
    markArrived(row: any) {
      if (row.isReceive) return;
      row.isReceive = true;
      const now = new Date();
  row.arrivalTime = now.toISOString();
  row.deliverDurationDays = this.calcDurationDays(row.deliverTime, row.arrivalTime);
      this.showToast('success', '成功', '已标记到货');
    }
    getImagesArray(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map((url) => environment.modifiedApiUrl + url);
      return urls;
    }
    launchReview() {
      const invalidStatus = this.CheckedRows.some(row => row.status === '审核通过' || row.status === '审核中')
      if (invalidStatus) {
          this.showToast('error', '错误', '所选单据已发起审核');
          return
      }
      if (this.checkedCodes.length < 1) {
        this.showToast('error', '错误', '请选择要发起审核的单据');
        return;
      }
      this.ReviewRolesService.StartApprovalFlow(
        '销售发货单审核流配置',
        this.checkedCodes
      ).subscribe(
        (res: any) => {
          this.showToast('success', '成功', res);
          this.filter();
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    }
    clickCode(code: string, type: string, status?: string, dialogtype?: string) {
      let data = {
        code: code,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '90vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: ReviewDocComponent,
        dialogtype: dialogtype,
        data:data,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '通过',
            handler: ($event: Event) => {
              if(results.modalContentInstance.approvalNodeId){
              this.ReviewRolesService.ApproveNode(
                results.modalContentInstance.approvalNodeId,
                code
              ).subscribe((res: any) => {
                results.modalInstance.hide();
                this.showToast('success', '成功', '审批成功');
                this.filter();
              },error=>{
                this.showToast('error', '错误', error.error || '网络连接错误');
              }
            );
            }
            else{
              this.showToast('error', '错误', '没有需要审批的节点');
            }
            },
          },
          {
            cssClass: 'danger',
            text: '驳回',
            handler: ($event: Event) => {
              if(results.modalContentInstance.approvalNodeId){
                console.log()
              if(results.modalContentInstance.reason){
                this.ReviewRolesService.RejectNode(
                  results.modalContentInstance.approvalNodeId,
                  code,
                  results.modalContentInstance.reason
                ).subscribe(
                  (res) => {
                    this.showToast('success', '成功', '审批成功');
                    results.modalInstance.hide();
                    this.filter();
                  },
                  (error: any) => {
                    this.showToast(
                      'error',
                      '错误',
                      error.error || '网络连接错误'
                    );
                  }
                );
              }else{
                data.disPlay = true
                this.showToast('warn', '警告', '请填写驳回原因');
              }
            }else{
              this.showToast('error', '错误', '没有需要审批的节点');
            }
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    getImagesArray2(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
      return urls;
    }
}
